package  com.rh.soc.zonethirdinterface.service.impl;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rh.soc.bussinessdomainmanage.model.TreeVO;
import com.rh.soc.comm.center.IHostMonitor;
import com.rh.soc.management.systemconfig.appconfig.dao.IAppConfigDAO;
import com.rh.soc.management.systemconfig.appconfig.model.AgentServerInfoVO;
import com.rh.soc.management.systemconfig.menuconfig.model.OperaVO;
import com.rh.soc.securitydomainmanage.model.SecurityDomainBriefVO;
import com.rh.soc.securitydomainmanage.model.SecurityDomainVO;
import com.rh.soc.watch.gis.common.dao.IGISAddrDAO;
import com.rh.soc.watch.gis.common.model.GISAddrVO;
import com.rh.soc.zonethirdinterface.dao.IThirdSecurityDomainDAO;
import com.rh.soc.zonethirdinterface.dao.IThirdStaffManageDAO;
import com.rh.soc.zonethirdinterface.service.IThirdSecurityDomainService;
import com.rh.webserver.common.base.exception.AppException;
import com.rh.webserver.common.base.service.BaseService;
import com.rh.webserver.common.util.StringUtil;

/**
 * 
 * 
 */
@Service("thirdsecuritydomainservice")
@Transactional
@SuppressWarnings({ "unchecked", "unused" })
public class ThirdSecurityDomainServiceImpl extends BaseService implements IThirdSecurityDomainService {
	
	@Resource
	private IThirdSecurityDomainDAO securityDomainDAOImpl;

	@Resource
	private IThirdStaffManageDAO staffManageDAOImpl;
	
	@Resource
	private IGISAddrDAO gisAddrDAOImpl;
	
	@Resource
	private IAppConfigDAO iAppConfigDAOIml;

	private final Logger logger = Logger.getLogger("SOC_Error");

	/**
	 * 增加安全域信息
	 * 
	 * @param vo
	 * @return
	 * @throws AppException
	 */

	public SecurityDomainVO addSecurityDomain(SecurityDomainVO vo) throws AppException {
		try {
			// ************************************************************************************
			// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
			// 和删除时，对扫描区域表做操作
			String flag = "1";
			// ************************************************************************************
			SecurityDomainVO revo = new SecurityDomainVO();
			String level = securityDomainDAOImpl.querySingleDomaLevel(vo.getPdomaId());
			if ("6".equals(level)) {
				revo.setFlag(6);
				return revo;

			}
			// 查询当前的local_code 域ID初始化数据定死为IMAP --2012/02/02邵珅
			// String id = securityDomainDAOImpl.queryLocal("0", "1");
			String id = vo.getDomaId();
			if (StringUtil.isEmpty(vo.getDomaId())) {
				id = "IMAP";
				id += this.nextValue("SEQ_DOMAIN_DICT");
				vo.setDomaId(id);
			}
			int i;

			// 判断安全域编号是否存在
			int isExitVo = securityDomainDAOImpl.checkSecurityIsExists(vo.getDomaId());
			if (isExitVo > 0) {
				revo.setFlag(-9);
				return revo;
			}
			// // 判断安全域父编号是否存在
			// int isExitPVo =
			// securityDomainDAOImpl.checkSecurityIsExists(vo.getPdomaId());
			// if (isExitPVo==0) {
			// revo.setFlag(-10);
			// return revo;
			// }

//			// 判断代理是否存在
//			AgentServerInfoVO agentServerInfoVO = new AgentServerInfoVO();
//			agentServerInfoVO.setAppId(vo.getNodeId());
//			List<AgentServerInfoVO> agentServerInfoVOList = iAppConfigDAOIml.queryAgentInitInfo(agentServerInfoVO);
//			if (null == agentServerInfoVOList || agentServerInfoVOList.size() == 0) {
//				revo.setFlag(-11);
//				return revo;
//			}

			i = securityDomainDAOImpl.queryDomaName(vo.getDomaName(), vo.getPdomaId(), vo.getDomaId());
			if (i < 0) {
				revo.setFlag(i);
				return revo;

			} else {
				// 判断安全域简称是否存在
				i = securityDomainDAOImpl.queryDomaAbbreviation(vo.getDomaAbbreviation(), vo.getPdomaId(),
						vo.getDomaId());
				if (i < 0) {
					revo.setFlag(i);
					return revo;
				} else {
					// 查询同级域的下一个权重值
					vo.setDomaClass("1");
					String nextSort = securityDomainDAOImpl.queryNextSort(vo);
					vo.setDomaSort(nextSort);
					// 添加安全域
					i = securityDomainDAOImpl.addSecurityDomain(vo);
					// 添加与域对应的组织Id
					@SuppressWarnings("unused")
					String ss_id = securityDomainDAOImpl.addStaffStructure(vo.getDomaId(), vo.getDomaName());
					// 添加域所属的代理引擎
					securityDomainDAOImpl.addDomainVsAgent(vo.getDomaId(), vo.getNodeId());
					// ************************************************************************************
					// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
					// 和删除时，对扫描区域表做操作
					if ("1".equals(flag)) {
						String pathDomaName = "";
						if (!"-1".equals(vo.getPdomaId())) {
							// 在添加扫描区域前，先根据新添加的域的Id查出全路径
							pathDomaName = securityDomainDAOImpl.querySDNamePath(vo.getPdomaId());
							pathDomaName += ">" + vo.getDomaName();
						} else { // 添加扫描区域信息
							pathDomaName += vo.getDomaName();
						}

						vo.setDomaName(pathDomaName);
						securityDomainDAOImpl.addScanZone(vo);// 暂时先这样写，向扫描区域表中添加数据
					}
					// ************************************************************************************

					// 添加gis表
					if (StringUtils.isNotEmpty(vo.getGisX())) {
						GISAddrVO gisVO = new GISAddrVO();
						gisVO.setObjectType("1");// 安全域
						gisVO.setObjectId(vo.getDomaId());
						gisVO.setGisX(vo.getGisX());
						gisVO.setGisY(vo.getGisY());
						gisAddrDAOImpl.addGis(gisVO);
					}

					revo.setFlag(i);
					revo.setDomaId(id);
					// revo.setSsId(ss_id);

					// 更新代理ID，需要通知后台
					IHostMonitor hostMonitor = this.getRemoteInstance(IHostMonitor.class);
					boolean returnFlag =hostMonitor.modifyServerDomain();
					
					logger.info("增加 returnFlag=" + returnFlag);
					logger.info("增加 revo " + revo);

					return revo;

				}
			}
		} catch (Exception e) {
			logger.error("添加安全域失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 
	 * 删除安全域信息
	 * @param vo
	 * @return
	 * @throws AppException
	 */

	public String deleteSecurityDomain(SecurityDomainVO vo) throws AppException {

		try {

			int isExistDomain = securityDomainDAOImpl.checkSecurityIsExistsForDelete(vo.getDomaId());
			if (isExistDomain == 0) {
				return "-9";
			}

			// ************************************************************************************
			// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
			// 和删除时，对扫描区域表做操作
			String flag = "1";
			// ************************************************************************************
			String delId[] = null;// 要删除的doma_id组成的数组
			String deleid = null;// 要删除的doma_id组成的字符串
			String delName[] = null;
			/*
			 * if(vo.getDelFlag().equals("1")) {//单个删除
			 */vo.setDelIds(vo.getDomaId());
			vo.setDelNames(vo.getDomaName());
			// deleid = vo.getDomaId();

			/* }else{ */
			deleid = securityDomainDAOImpl.queryChildDomain(vo);// 根据vo.getDelIds()得到的选中的删除id
																// 去后台进行递归查询。
			vo.setDomaId(deleid);
			/* } */
			// 查询该域下是否存在资产，若存在，则不删除，给出提示信息
			String isHasDevices = securityDomainDAOImpl.isHasDevice(deleid);
			if (Integer.valueOf(isHasDevices) > 0) {
				// 安全域下有资产
				return "2";
			} else if ("-1".equals(isHasDevices)) {
				// 安全域下有备用资产
				return "-1";
			}
			// vo.setDomaId(deleid);
			// ************************************************************************************
			if ("1".equals(flag)) {
				securityDomainDAOImpl.delNetWork(vo);
				securityDomainDAOImpl.updateAgentType();
				// 删除扫描区域的表信息
				securityDomainDAOImpl.delScanZone(vo);
			}
			// ************************************************************************************
			securityDomainDAOImpl.deleteSecurityDomain(vo);
			securityDomainDAOImpl.delDomainVsAgentBatch(vo);

			// 删除数据权限表中对应数据
			securityDomainDAOImpl.delUserVsGrants(vo);

			// 删除安全域gis信息
			GISAddrVO gisVO = new GISAddrVO();
			gisVO.setObjectType("1");// 安全域
			gisVO.setObjectId(vo.getDomaId());

			gisAddrDAOImpl.delGis(gisVO);
			// securityDomainDAOImpl.delGis(vo);

			return "0";
		} catch (Exception e) {
			logger.error("删除安全域失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 增加安全域信息
	 * @param vo
	 * @return
	 * @throws AppException
	 */

	public SecurityDomainVO updAndAddSecurityDomain(SecurityDomainVO vo) throws AppException {
		try {
			// ************************************************************************************
			// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
			// 和删除时，对扫描区域表做操作
			String flag = "1";
			// ************************************************************************************
			SecurityDomainVO revo = new SecurityDomainVO();
			String level = securityDomainDAOImpl.querySingleDomaLevel(vo.getPdomaId());
			if ("6".equals(level)) {
				revo.setFlag(6);
				return revo;

			}
			// 查询当前的local_code 域ID初始化数据定死为IMAP --2012/02/02邵珅
			// String id = securityDomainDAOImpl.queryLocal("0", "1");
			String id = vo.getDomaId();
			if (StringUtil.isEmpty(vo.getDomaId())) {
				id = "IMAP";
				id += this.nextValue("SEQ_DOMAIN_DICT");
				vo.setDomaId(id);
			}
			int i;

			// // 判断安全域父编号是否存在
			// int isExitPVo =
			// securityDomainDAOImpl.checkSecurityIsExists(vo.getPdomaId());
			// if (isExitPVo==0) {
			// revo.setFlag(-10);
			// return revo;
			// }

			// 判断代理是否存在
			AgentServerInfoVO agentServerInfoVO = new AgentServerInfoVO();
			agentServerInfoVO.setAppId(vo.getNodeId());
			List<AgentServerInfoVO> agentServerInfoVOList = iAppConfigDAOIml.queryAgentInitInfo(agentServerInfoVO);
			if (null == agentServerInfoVOList || agentServerInfoVOList.size() == 0) {
				revo.setFlag(-11);
				return revo;
			}

			/**
			 * 判断安全域编号是否存在 如果存在则修改，如果不存在则添加
			 */
			int isExitVo = securityDomainDAOImpl.checkSecurityIsExists(vo.getDomaId());
			
			if (isExitVo > 0) {
				
//				// 判断业务域名称是否存在
//				i = securityDomainDAOImpl.queryDomaName(vo.getDomaName(), vo.getPdomaId(), vo.getDomaId());
//				if (i < 0) {
//					revo.setFlag(i);
//
//					return revo;
//				}
//				// 判断业务域简称是否存在
//				i = securityDomainDAOImpl.queryDomaAbbreviation(vo.getDomaAbbreviation(), vo.getPdomaId(), vo.getDomaId());
//				if (i < 0) {
//					revo.setFlag(i);
//
//					return revo;
//				}
				if (StringUtils.isNotEmpty(vo.getNewNodeId())) {
					List<SecurityDomainVO> result = null;
					result = securityDomainDAOImpl.queryIsExistIp(vo);
					if (result.size() > 0) {
						// 代理下的网段信息重复
						revo.setFlag(-4);
						revo.setMessage(makeEdAlertInfo(result));
						return revo;
					}
				}
				if (!vo.getPdomaId().equals(vo.getOldPdomaId())) {
					// 当父安全域改变时，需要同时修改该域的权值。
					vo.setDomaClass("1");
					String nextSort = securityDomainDAOImpl.queryNextSort(vo);
					vo.setDomaSort(nextSort);
				} else {
					// 若父安全域未修改，重新获取下该域的权重
					vo.setDomaSort(securityDomainDAOImpl.queryDomaSort(vo));
				}
				// 修改 t_domain_dict 表中的记录
				securityDomainDAOImpl.updateSecurityDomain(vo);
				// 删除 t_domain_vs_agent 表中的记录
				// securityDomainDAOImpl.delDomainVsAgent(vo.getDomaId());
				// 添加域所属的代理引擎
				// securityDomainDAOImpl.addDomainVsAgent(vo.getDomaId(), vo.getNodeId());
				// 修改 t_staff_structure 表中的记录
				securityDomainDAOImpl.updateStaffStructure(vo.getDomaName(), vo.getDomaId());
				// ************************************************************************************
				// 修改扫描区域
				if ("1".equals(flag)) {
					String pathDomaName = "";
					if (!"-1".equals(vo.getPdomaId())) {
						// 在添加扫描区域前，先根据新添加的域的Id查出全路径
						pathDomaName = securityDomainDAOImpl.querySDNamePath(vo.getPdomaId());
						pathDomaName += ">" + vo.getDomaName();
					} else { // 添加扫描区域信息
						pathDomaName += vo.getDomaName();
					}

					vo.setDomaName(pathDomaName);
					securityDomainDAOImpl.updScanZone(vo.getDomaName(), vo.getDomaId());
				}
				// ************************************************************************************

				// 修改gis表，先删除，再插入新数据
				if (StringUtils.isNotEmpty(vo.getGisX())) {
					GISAddrVO gisVO = new GISAddrVO();
					gisVO.setObjectType("1");// 安全域
					gisVO.setObjectId(vo.getDomaId());
					gisVO.setGisX(vo.getGisX());
					gisVO.setGisY(vo.getGisY());

					gisAddrDAOImpl.delGis(gisVO);
					gisAddrDAOImpl.addGis(gisVO);

				}

				// 修改成功，使标志值置1.
				revo.setFlag(1);
				revo.setDomaId(vo.getDomaId());

				// 更新代理ID，需要通知后台
				IHostMonitor hostMonitor = this.getRemoteInstance(IHostMonitor.class);
				hostMonitor.modifyServerDomain();

				return revo;
				
			}
			else{
				
				// 查询同级域的下一个权重值
				vo.setDomaClass("1");
				String nextSort = securityDomainDAOImpl.queryNextSort(vo);
				vo.setDomaSort(nextSort);
				// 添加安全域
				i = securityDomainDAOImpl.addSecurityDomain(vo);
				// 添加与域对应的组织Id
				@SuppressWarnings("unused")
				String ss_id = securityDomainDAOImpl.addStaffStructure(vo.getDomaId(), vo.getDomaName());
				// 添加域所属的代理引擎
				securityDomainDAOImpl.addDomainVsAgent(vo.getDomaId(), vo.getNodeId());
				// ************************************************************************************
				// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
				// 和删除时，对扫描区域表做操作
				if ("1".equals(flag)) {
					String pathDomaName = "";
					if (!"-1".equals(vo.getPdomaId())) {
						// 在添加扫描区域前，先根据新添加的域的Id查出全路径
						pathDomaName = securityDomainDAOImpl.querySDNamePath(vo.getPdomaId());
						pathDomaName += ">" + vo.getDomaName();
					} else { // 添加扫描区域信息
						pathDomaName += vo.getDomaName();
					}

					vo.setDomaName(pathDomaName);
					securityDomainDAOImpl.addScanZone(vo);// 暂时先这样写，向扫描区域表中添加数据
				}
				// ************************************************************************************

				// 添加gis表
				if (StringUtils.isNotEmpty(vo.getGisX())) {
					GISAddrVO gisVO = new GISAddrVO();
					gisVO.setObjectType("1");// 安全域
					gisVO.setObjectId(vo.getDomaId());
					gisVO.setGisX(vo.getGisX());
					gisVO.setGisY(vo.getGisY());
					gisAddrDAOImpl.addGis(gisVO);
				}

				revo.setFlag(i);
				revo.setDomaId(id);
				// revo.setSsId(ss_id);

				// 更新代理ID，需要通知后台
				IHostMonitor hostMonitor = this.getRemoteInstance(IHostMonitor.class);
				hostMonitor.modifyServerDomain();

				return revo;

			}


		} catch (Exception e) {
			logger.error("添加安全域失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 
	 * 查询安全域信息
	 * @param vo
	 * @return
	 * @throws AppException
	 */
	@SuppressWarnings("unchecked")
	public List<SecurityDomainVO> queryAllSecurityDomain() throws AppException {
		try {
			List<SecurityDomainVO> result = securityDomainDAOImpl.queryAllTree();
			List<SecurityDomainVO> last = new ArrayList<SecurityDomainVO>();
			// 删除根节点
			for (SecurityDomainVO domain : result) {
				if ("2".equals(domain.getLevel())) {
					List<SecurityDomainVO> children = transTree(domain, result);
					domain.setChildren(children);
					last.add(domain);
				}
			}
			return last;
		} catch (Exception e) {
			String bussinessDomainAlias = "";
			try {
				// bussinessDomainAlias =
				// CodeListManager.getCodeListCache().getCodeName("bussinessDomainAlias","1");
			} catch (Exception e1) {
				e1.printStackTrace();
			} // 可配业务域名称
			logger.error("查询" + bussinessDomainAlias + "失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 
	 * {组装树形的函数}
	 * @param vo
	 * @param dataList
	 * @return
	 */
	private List<SecurityDomainVO> transTree(SecurityDomainVO vo, List<SecurityDomainVO> dataList) {
		List<SecurityDomainVO> result = new ArrayList<SecurityDomainVO>();

		if (!dataList.isEmpty()) {
			// 查询子节点
			for (SecurityDomainVO dataitem : dataList) {
				String conditionId = vo.getDomaId();
				if (dataitem.getPdomaId().equals(conditionId)) {
					result.add(dataitem);
				}
			}
			for (SecurityDomainVO domain : result) {
				List<SecurityDomainVO> children = transTree(domain, dataList);
				domain.setChildren(children);
			}
		}

		return result;
	}

	/**
	 * {组装树形的函数}
	 * @param vo
	 * @param dataList
	 * @return
	 */
	private List<SecurityDomainBriefVO> transTreeForBrief(SecurityDomainBriefVO vo,
			List<SecurityDomainBriefVO> dataList) {
		List<SecurityDomainBriefVO> result = new ArrayList<SecurityDomainBriefVO>();

		if (!dataList.isEmpty()) {
			// 查询子节点
			for (SecurityDomainBriefVO dataitem : dataList) {
				String conditionId = vo.getDomaId();
				if (dataitem.getPdomaId().equals(conditionId)) {
					result.add(dataitem);
				}
			}
			for (SecurityDomainBriefVO domain : result) {
				List<SecurityDomainBriefVO> children = transTreeForBrief(domain, dataList);
				domain.setChildren(children);
			}

		}

		return result;
	}

	/**
	 * 获取查询树形的节点路径列表
	 */
	public List<String> queryTreeWithCondition(SecurityDomainBriefVO vo) throws AppException {
		try {
			List result = new ArrayList();
			// step 1 //查询数据库中的所有可见的安全域数据
			List<SecurityDomainBriefVO> dataList = securityDomainDAOImpl.queryAllTreeForBrief();
			List<SecurityDomainBriefVO> allTree = new ArrayList<SecurityDomainBriefVO>();
			// 删除根节点
			for (SecurityDomainBriefVO domain : dataList) {
				// 数据库中域数据一共的层级数为6层，第一层为根节点，做为基础数据，不显示在页面上。
				if ("2".equals(domain.getLevel())) {
					// 组装树形的函数
					List<SecurityDomainBriefVO> children = transTreeForBrief(domain, dataList);
					domain.setPdomaId("");
					domain.setChildren(children);
					allTree.add(domain);
				}
			}

			if (vo != null) {
				List<SecurityDomainBriefVO> withCondition = securityDomainDAOImpl.queryTreeWithCondition(vo);
				List<String> treePath = new ArrayList<String>();
				if (!withCondition.isEmpty()) {
					for (SecurityDomainBriefVO item : withCondition) {
						treePath.add((item.getTreePath()).replace("-1,", ""));
					}
				}
				// 调用树形工具初始化函数
				// sectreeOperateImpl.init(SecurityDomainBriefVO.class,
				// "domaId", "pdomaId", "children");
				// 根据传入的路径,查找树形的路径
				// result = sectreeOperateImpl.getTreeWithPath(allTree,
				// treePath, ",");
			} else {
				result = allTree;
			}
			return result;
		} catch (Exception e) {
			logger.error("数据获取失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 获取子节点
	 */
	public List<SecurityDomainBriefVO> queryTreeChildrenList(SecurityDomainBriefVO vo) throws AppException {
		try {

			List result = new ArrayList();
			// step 1 //查询数据库中的所有可见的安全域数据
			List<SecurityDomainBriefVO> dataList = securityDomainDAOImpl.queryTreeChildrenList(vo);
			// List<SecurityDomainBriefVO> allTree = new
			// ArrayList<SecurityDomainBriefVO>();
			// // 删除根节点
			// for (SecurityDomainBriefVO domain : dataList) {
			// // 组装树形的函数
			// List<SecurityDomainBriefVO> children = transTreeForBrief(domain,
			// dataList);
			// domain.setChildren(children);
			// allTree.add(domain);
			//
			// }
			// result = allTree;

			return dataList;
		} catch (Exception e) {
			logger.error("数据获取失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 
	 * 查询安全域的详细信息
	 * 
	 * @param domaId
	 * @return
	 * @throws AppException

	 */

	public SecurityDomainVO querySecurityDetail(String domaId) throws AppException {
		try {
			SecurityDomainVO vo = securityDomainDAOImpl.querySecurityDetail(domaId);
			vo.setNodeId(securityDomainDAOImpl.queryNodeId(domaId));
			vo.setNodeName(securityDomainDAOImpl.queryNodeName(domaId));
			if ("-1".equals(vo.getPdomaId())) {
				vo.setPdomaId("");
			}
			return vo;
		} catch (Exception e) {
			logger.error("查询安全域具体信息失败。", e);
			throw new AppException(e);
		}
	}

	/**
	 * 
	 * 更新安全域信息
	 * 
	 * @param vo
	 * @return
	 * @throws AppException

	 */
	public SecurityDomainVO updateSecurityDomain(SecurityDomainVO vo) throws AppException {
		SecurityDomainVO revo = new SecurityDomainVO();
		// ************************************************************************************
		// 当前并不确定项目所定的是安全域还是业务域，因此关联到扫描区域的部分也不确定，暂时定为已安全域为主，因此当添加和修改和
		// 和删除时，对扫描区域表做操作
		String flag = "1";// 是否修改扫描区域的标志
		// ************************************************************************************
		String level = securityDomainDAOImpl.querySingleDomaLevel(vo.getPdomaId());
		if ("6".equals(level)) {
			revo.setFlag(6);
			return revo;

		}
		int isExistDomain = securityDomainDAOImpl.checkSecurityIsExistsForDelete(vo.getDomaId());
		int i;
		if (isExistDomain == 0) {
			revo.setFlag(-1);

			return revo;
		}

		// // 判断安全域父编号是否存在
		// int isExitPVo =
		// securityDomainDAOImpl.checkSecurityIsExistsForDelete(vo.getPdomaId());
		// if (0 == isExitPVo) {
		// revo.setFlag(-10);
		// return revo;
		// }

		// 判断代理是否存在
//		AgentServerInfoVO agentServerInfoVO = new AgentServerInfoVO();
//		agentServerInfoVO.setAppId(vo.getNodeId());
//		List<AgentServerInfoVO> agentServerInfoVOList = iAppConfigDAOIml.queryAgentInitInfo(agentServerInfoVO);
//		if (null == agentServerInfoVOList || agentServerInfoVOList.size() == 0) {
//			revo.setFlag(-11);
//			return revo;
//		}

		List<SecurityDomainVO> result = null;
		try {

			// 判断业务域名称是否存在
			i = securityDomainDAOImpl.queryDomaName(vo.getDomaName(), vo.getPdomaId(), vo.getDomaId());
			if (i < 0) {
				revo.setFlag(i);

				return revo;
			}
			// 判断业务域简称是否存在
			i = securityDomainDAOImpl.queryDomaAbbreviation(vo.getDomaAbbreviation(), vo.getPdomaId(), vo.getDomaId());
			if (i < 0) {
				revo.setFlag(i);

				return revo;
			}
			if (StringUtils.isNotEmpty(vo.getNewNodeId())) {
				result = securityDomainDAOImpl.queryIsExistIp(vo);
				if (result.size() > 0) {
					// 代理下的网段信息重复
					revo.setFlag(-4);
					revo.setMessage(makeEdAlertInfo(result));

					return revo;
				}
			}
			if (!vo.getPdomaId().equals(vo.getOldPdomaId())) {
				// 当父安全域改变时，需要同时修改该域的权值。
				vo.setDomaClass("1");
				String nextSort = securityDomainDAOImpl.queryNextSort(vo);
				vo.setDomaSort(nextSort);
			} else {
				// 若父安全域未修改，重新获取下该域的权重
				vo.setDomaSort(securityDomainDAOImpl.queryDomaSort(vo));
			}
			// 修改 t_domain_dict 表中的记录
			securityDomainDAOImpl.updateSecurityDomain(vo);
			// 删除 t_domain_vs_agent 表中的记录
//			securityDomainDAOImpl.delDomainVsAgent(vo.getDomaId());
			// 添加域所属的代理引擎
//			securityDomainDAOImpl.addDomainVsAgent(vo.getDomaId(), vo.getNodeId());
			// 修改 t_staff_structure 表中的记录
			securityDomainDAOImpl.updateStaffStructure(vo.getDomaName(), vo.getDomaId());
			// ************************************************************************************
			// 修改扫描区域
			if ("1".equals(flag)) {
				String pathDomaName = "";
				if (!"-1".equals(vo.getPdomaId())) {
					// 在添加扫描区域前，先根据新添加的域的Id查出全路径
					pathDomaName = securityDomainDAOImpl.querySDNamePath(vo.getPdomaId());
					pathDomaName += ">" + vo.getDomaName();
				} else { // 添加扫描区域信息
					pathDomaName += vo.getDomaName();
				}

				vo.setDomaName(pathDomaName);
				securityDomainDAOImpl.updScanZone(vo.getDomaName(), vo.getDomaId());
			}
			// ************************************************************************************

			// 修改gis表，先删除，再插入新数据
			if (StringUtils.isNotEmpty(vo.getGisX())) {
				GISAddrVO gisVO = new GISAddrVO();
				gisVO.setObjectType("1");// 安全域
				gisVO.setObjectId(vo.getDomaId());
				gisVO.setGisX(vo.getGisX());
				gisVO.setGisY(vo.getGisY());

				gisAddrDAOImpl.delGis(gisVO);
				gisAddrDAOImpl.addGis(gisVO);

			}

			// 修改成功，使标志值置1.
			revo.setFlag(1);
			revo.setDomaId(vo.getDomaId());

			// 更新代理ID，需要通知后台
			IHostMonitor hostMonitor = this.getRemoteInstance(IHostMonitor.class);
			boolean returnFlag=hostMonitor.modifyServerDomain();
			
			logger.info("修改 returnFlag=" + returnFlag);
			logger.info("修改 revo " + revo);

			return revo;

		} catch (Exception e) {
			String bussinessDomainAlias = "";
			try {
				// bussinessDomainAlias =
				// CodeListManager.getCodeListCache().getCodeName("bussinessDomainAlias","1");
			} catch (Exception e1) {
				e1.printStackTrace();
			} // 可配业务域名称
			logger.error("修改" + bussinessDomainAlias + "信息失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 
	 * {修改需要互换位置的域信息}
	 * 
	 * @param list
	 * @return
	 * 
	 * @throws AppException
	 */
	public void updDomaSort(OperaVO vo) throws AppException {
		try {
			Map<String, Map<String, Object>> resultMap = new HashMap<String, Map<String, Object>>();
			try {
				if ("top".equals(vo.getPoint()) || "bottom".equals(vo.getPoint())) { // 拖拽到目标上、下
					SecurityDomainVO t = new SecurityDomainVO();
					t.setPdomaId(vo.getTargetPid());
					List<SecurityDomainVO> domaList = queryTree(t, false);
					SecurityDomainVO tmpvo = new SecurityDomainVO();
					tmpvo.setDomaId(vo.getSourceId());
					tmpvo.setPdomaId(vo.getTargetPid());
					domaList = handleDomainList(domaList, tmpvo, vo.getTargetId(), vo.getPoint());
					int orderId = 10;
					for (SecurityDomainVO tvo : domaList) {
						securityDomainDAOImpl.updDomain4Drop(tvo, orderId, vo.getPoint());
						orderId += 10;
					}
				}
			} catch (Exception e) {
				logger.error("数据修改失败", e);
				throw new AppException(e);
			}
		} catch (Exception e) {
			logger.error("修改权重信息失败。", e);
			throw new AppException(e);
		}
	}

	private List<SecurityDomainVO> handleDomainList(List<SecurityDomainVO> domaList, SecurityDomainVO vo,
			String targetId, String point) {
		if (!"append".equals(point)) {
			Iterator<SecurityDomainVO> it = domaList.iterator();
			while (it.hasNext()) {
				SecurityDomainVO _vo = it.next();
				if (_vo.getDomaId().equals(vo.getDomaId())) {
					it.remove();
					break;
				}
			}

			for (int i = 0; i < domaList.size(); i++) {
				SecurityDomainVO tmpvo = domaList.get(i);
				if (targetId.equals(tmpvo.getDomaId())) {
					if ("top".equals(point)) {
						// 拖拽到目标节点上，在目标节点前添加节点
						domaList.add(i, vo);
						break;
					} else {
						// 拖拽到目标节点上，在目标节点后添加节点
						if (i == domaList.size()) {
							// 若目标节点为当前list中最后一个节点，直接添加
							domaList.add(vo);
						} else {
							// 若目标节点不为当前list中最后一个节点，序列增加1后添加到指定位置
							domaList.add(i + 1, vo);
						}
						break;
					}
				}
			}
		}
		return domaList;
	}

	/**
	 * 
	 * 返回网段重复的提示信息
	 * 
	 * @param result
	 * @return

	 */
	private String makeEdAlertInfo(List<SecurityDomainVO> result) {
		StringBuilder info = new StringBuilder();
		info.append("所选网段中的IP已经被其他代理引擎占用，详细信息如下：").append("<br/>");

		for (SecurityDomainVO vo : result) {
			info.append("代理名称").append(vo.getAgent_name()).append("&nbsp;&nbsp;");
			info.append("域下网段名称:").append(vo.getDoma_ip_name()).append("&nbsp;&nbsp;");
			info.append("起始IP：").append(vo.getDoma_ip_start()).append("&nbsp;&nbsp;");
			info.append("终止IP：").append(vo.getDoma_ip_end()).append("&nbsp;&nbsp;");

			info.append("代理下网段名称：").append(vo.getAgent_ip_name()).append("&nbsp;&nbsp;");
			info.append("起始IP：").append(vo.getAgent_ip_start()).append("&nbsp;&nbsp;");
			info.append("终止IP：").append(vo.getAgent_ip_end()).append("&nbsp;&nbsp;");
			info.append("域名称").append(vo.getPdomaName()).append("<br/>");

		}

		return info.toString();
	}

	/**
	 * 
	 * 删除人员信息 删除域时用到 现在已经不用了
	 * 
	 * @param staffId
	 * @return
	 * @throws AppException

	 */
	public void delStaff(SecurityDomainVO vo) throws AppException {
		try {

			String staffId = vo.getStaffId();
			String userId = vo.getUserId();
			if (StringUtils.isNotEmpty(userId)) {
				String userIdExists = securityDomainDAOImpl.queryRoleIsExists(vo);
				// 删除用户角色
				if (StringUtils.isNotEmpty(userIdExists)) {
					staffManageDAOImpl.delRoleId(userIdExists);

				}
				staffManageDAOImpl.delUserInfo(userId);

			}
			staffManageDAOImpl.delStaff(staffId);
		} catch (Exception e) {
			logger.error("删除人员失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 
	 * 递归查询域的子域，并将子域作为该域的孩子节点属性
	 * 
	 * @param vo
	 * @return

	 */
	public List<SecurityDomainVO> queryTree(SecurityDomainVO vo, boolean recurse) {
		List<SecurityDomainVO> result = securityDomainDAOImpl.querySubDomain(vo);
		if (recurse) {
			int intlevel = Integer.parseInt(vo.getLevel());
			String level = Integer.toString(intlevel++);
			for (SecurityDomainVO domain : result) {
				domain.setLevel(level);
				vo.setLevel(level);
				vo.setPdomaId(domain.getDomaId());
				List<SecurityDomainVO> children = queryTree(vo);
				domain.setChildren(children);
			}
		}
		return result;

	}

	public List<SecurityDomainVO> queryTree(SecurityDomainVO vo) {
		return queryTree(vo, true);
	}

	/**
	 * 
	 * 获取安全域树信息 页面上的隶属安全域为树形显示，执行该方法
	 * 
	 * @param vo
	 * @return
	 * @throws AppException

	 */
	public List<TreeVO> querySecurityDomainTree(TreeVO vo) throws AppException {
		try {
			List<TreeVO> resultList = securityDomainDAOImpl.querySecurityDomainTree(vo);
			// TreeVO tvo = new TreeVO();
			// tvo.setId("roota");
			// tvo.setParentID("root");
			// tvo.setLeaf(false);
			// tvo.setLabel("业务域");
			// resultList.add(tvo);
			return resultList;
		} catch (Exception e) {
			logger.error("数据获取失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 
	 * {验证域是否有子域}
	 * 
	 * @param domaId
	 * @return
	 * 
	 * @throws AppException
	 */
	public String checkDomain(String domaId, String domaClass) throws AppException {
		try {
			SecurityDomainVO vo = new SecurityDomainVO();
			vo.setDelIds(domaId);
			vo.setDomaClass(domaClass);
			return securityDomainDAOImpl.checkChildDomain(vo);
		} catch (Exception e) {
			logger.error("数据获取失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 查询安全域列表（华能定制）
	 * 
	 * @return
	 * @throws AppException

	 */
	public String querySecurityDomainForHuaneng() throws AppException {
		List<SecurityDomainVO> list = this.securityDomainDAOImpl.queryAllTree();
		Document d = DocumentHelper.createDocument();
		d.setXMLEncoding("gbk");
		Element securityDomainRoot = d.addElement("root");
		Element securityDomains = securityDomainRoot.addElement("securityDomains");
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			SecurityDomainVO securityDomainVO = (SecurityDomainVO) iterator.next();
			Element securityDomain = securityDomains.addElement("securityDomain");
			securityDomain.addElement("domaId")
					.setText(securityDomainVO.getDomaId() == null ? "" : securityDomainVO.getDomaId());
			securityDomain.addElement("pdomaId")
					.setText(securityDomainVO.getPdomaId() == null ? "" : securityDomainVO.getPdomaId());
			securityDomain.addElement("pdomaName")
					.setText(securityDomainVO.getPdomaName() == null ? "" : securityDomainVO.getPdomaName());
			securityDomain.addElement("domaName")
					.setText(securityDomainVO.getDomaName() == null ? "" : securityDomainVO.getDomaName());
			securityDomain.addElement("domaAbbreviation").setText(
					securityDomainVO.getDomaAbbreviation() == null ? "" : securityDomainVO.getDomaAbbreviation());
			securityDomain.addElement("officeTel")
					.setText(securityDomainVO.getOfficeTel() == null ? "" : securityDomainVO.getOfficeTel());
			securityDomain.addElement("email")
					.setText(securityDomainVO.getEmail() == null ? "" : securityDomainVO.getEmail());
			securityDomain.addElement("faxNo")
					.setText(securityDomainVO.getFaxNo() == null ? "" : securityDomainVO.getFaxNo());
			securityDomain.addElement("complaintTel")
					.setText(securityDomainVO.getComplaintTel() == null ? "" : securityDomainVO.getComplaintTel());
			securityDomain.addElement("domaAddress")
					.setText(securityDomainVO.getDomaAddress() == null ? "" : securityDomainVO.getDomaAddress());
			securityDomain.addElement("nodeName")
					.setText(securityDomainVO.getNodeName() == null ? "" : securityDomainVO.getNodeName());
			securityDomain.addElement("domaMemo")
					.setText(securityDomainVO.getDomaMemo() == null ? "" : securityDomainVO.getDomaMemo());
		}
		return d.asXML();
	}

	/**
	 * 
	 * {获取域信息}
	 * 
	 * @param vo
	 * @return
	 * 
	 * @throws AppException
	 */
	public String queryDomaList(String domaClass) throws AppException {
		String xml = ""; // 同步ITSM的XML
		String resultXml = ""; // 返回值XML
		String result = "0"; // 结果值
		try {
			List<SecurityDomainVO> list = securityDomainDAOImpl.queryAllTreeByClass(domaClass);
			if (list.size() > 0) {
				// 创建XML结构
				Document document = DocumentHelper.createDocument();
				document.setXMLEncoding("gbk");
				Element root = document.addElement("root");
				for (SecurityDomainVO vo : list) {
					Element doma = root.addElement("doma");
					doma.addElement("pdomaId").setText(StringUtils.isEmpty(vo.getPdomaId()) ? "" : vo.getPdomaId());
					doma.addElement("domaId").setText(StringUtils.isEmpty(vo.getDomaId()) ? "" : vo.getDomaId());
					doma.addElement("domaName").setText(StringUtils.isEmpty(vo.getDomaName()) ? "" : vo.getDomaName());
					doma.addElement("domaClass").setText(domaClass);
					doma.addElement("domaAbbreviation")
							.setText(StringUtils.isEmpty(vo.getDomaAbbreviation()) ? "" : vo.getDomaAbbreviation());
					doma.addElement("domaSort").setText(StringUtils.isEmpty(vo.getDomaSort()) ? "" : vo.getDomaSort());
				}
				xml = document.asXML().toString();

				String IAName = ""; // 调用ITSM接口名称
				if ("1".equals(domaClass)) {
					IAName = "securityarea_sync";
				} else {
					IAName = "bsarea_sync";
				}
				// 调用ITSM接口
				// resultXml = ITSMClient.doITSMService(IAName, xml);
				// resultXml =
				// "<root><code>1</code><rootElement>成功</rootElement></root>";
			}
		} catch (Exception e) {
			logger.error("同步ITSM失败", e);
			throw new AppException(e);
		}
		if (StringUtils.isEmpty(resultXml)) {
			return result;
		}
		// 解析返回XML结构
		try {
			// 格式化XML结构
			if (resultXml.indexOf("?>") == -1) {
				resultXml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" + resultXml;
			} else {
				resultXml = resultXml.substring(resultXml.indexOf("?>") + 2, resultXml.length());
				resultXml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" + resultXml;
			}
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new ByteArrayInputStream(resultXml.getBytes()));
			Element root = document.getRootElement();
			if (root != null) {
				result = root.element("code").getText();
			}
		} catch (Exception e) {
			logger.error("解析返回值失败", e);
			throw new AppException(e);
		}

		return result;
	}

	/**
	 * gisAddrDAOImpl的GET方法
	 * 
	 * @return IGISAddrDAO gisAddrDAOImpl.
	 */
	public IGISAddrDAO getGisAddrDAOImpl() {
		return gisAddrDAOImpl;
	}

	/**
	 * gisAddrDAOImpl的SET方法
	 * 
	 * @param gisAddrDAOImpl
	 *            The gisAddrDAOImpl to set.
	 */
	public void setGisAddrDAOImpl(IGISAddrDAO gisAddrDAOImpl) {
		this.gisAddrDAOImpl = gisAddrDAOImpl;
	}

}
